package net.xdclass.xdclass.controller;

import net.xdclass.xdclass.model.request.LoginRequest;
import net.xdclass.xdclass.service.UserService;
import net.xdclass.xdclass.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("api/v1/pri/user")
public class UserController {

    @Autowired
    UserService userService;
    @PostMapping("/register")
    public JsonData register(@RequestBody Map<String,String> userInfo ){
        int i = userService.save(userInfo);
        return i==1?JsonData.buildSuccess("保存成功"):JsonData.buildError("注册失败，请重试");
    }


    @PostMapping("/login")
    public JsonData login(@RequestBody LoginRequest request){
        String token = userService.findByPhoneAndPwd(request.getPhone(),request.getPwd());
        return token==null?JsonData.buildError("登录失败，用户名或密码错误"):JsonData.buildSuccess(token);
    }

    @GetMapping("/find_by_token")
    public JsonData findUserInfoByToken(HttpServletRequest request){
        Integer userId = (Integer)request.getAttribute("user_id");
        if (userId==null){
           return JsonData.buildError("查询失败，用户名不存在");
        }else {
           User user = userService.findByUserId(userId);
           return JsonData.buildSuccess(user);
        }


    }
}
